package com.nowcoder.community.event.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.nowcoder.community.event.CommentEvent;
import com.nowcoder.community.event.FollowEvent;
import com.nowcoder.community.event.LikeEvent;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DefaultEventProducer {
    @Autowired
    private KafkaTemplate<String, Object>  kafkaTemplate;

    private void send(String topic, String content) {
        kafkaTemplate.send(topic, content);
        log.debug("发送消息 TO <{}>: {}", topic, content);
    }

    public void sendCommentEvent(CommentEvent event) {
        try {
            send(Constants.USER_COMMENT_TOPIC, CommunityUtils.toJson(event));
        } catch (JsonProcessingException e) {
            log.error("发送消息到{}失败, 无法将Event对象转成JSON数据. Event: {}, Cause: {}", Constants.USER_COMMENT_TOPIC, event, e.getMessage());
            // throw new RuntimeException(e);
        }
    }

    public void sendLikeEvent(LikeEvent event) {
        try {
            send(Constants.USER_LIKE_TOPIC, CommunityUtils.toJson(event));
        } catch (JsonProcessingException e) {
            log.error("发送消息到{}失败, 无法将Event对象转成JSON数据. Event: {}, Cause: {}", Constants.USER_COMMENT_TOPIC, event, e.getMessage());
            // throw new RuntimeException(e);
        }
    }

    public void sendFollowEvent(FollowEvent event) {
        try {
            send(Constants.USER_FOLLOW_TOPIC, CommunityUtils.toJson(event));
        } catch (JsonProcessingException e) {
            log.error("发送消息到{}失败, 无法将Event对象转成JSON数据. Event: {}, Cause: {}", Constants.USER_COMMENT_TOPIC, event, e.getMessage());
            // throw new RuntimeException(e);
        }
    }
}
